const fs = require('fs');
const path = require('path');
const MusicPage = require("./MusicPage");
const {sleep} = require("./Helper");
const Config = require("./Config");


class PlayList
{
    /**
     * @type {BrowserManager | null}
     */
    #browserManager = null;

    /**
     *
     * @type {User|null}
     */
    #user = null;
    constructor(browserManager,user)
    {
        this.#browserManager = browserManager
        this.#user = user;
    }


    async createPlayList()
    {
        const url = 'https://music.163.com/';
        const userInfo = await this.#user.getProfile();
        const userUrl = 'https://music.163.com/#/user/home?id='+userInfo.user_id;

        await sleep(1000);
        const userPage = await this.#browserManager.openPage(userUrl,this.#user.getCookie());

        const playListUrls = await MusicPage.getPlayListUrls(userPage)
        await userPage.close();
        if (playListUrls === null)
        {
            console.log('没找到 playListUrls');
            return ;
        }
        await sleep(1000);
        console.log('playListUrls:', playListUrls);

        const dirPath = Config.playListDir
        try {
            // 删除整个文件夹及内部所有文件
            fs.rmSync(dirPath, { recursive: true, force: true });
            console.log(`✅ 已删除文件夹: ${dirPath}`);
        } catch (err) {
            console.error(`❌ 删除文件夹失败: ${err.message}`);
        }
        if (!fs.existsSync(dirPath)) {
            fs.mkdirSync(dirPath, { recursive: true });
        }

        for (const playListUrl of playListUrls)
        {
            const playListPage = await this.#browserManager.openPage(playListUrl,this.#user.getCookie());

            console.log('歌单:', playListUrl);
            const musicUrls = await MusicPage.getMusicUrls(playListPage);

            console.log('获取到的歌单条目:', musicUrls.length);
            await playListPage.close();

            //创建一个目录 名字为 playList
            // 从 playListUrl https://music.163.com/#/playlist?id=7025612095
            // 获取 id;
            // 创建 文件 {id}.txt
            // 然后写入 musicUrls 的 json 进 {id}.txt
            // 创建目录 playList


            // 从 URL 获取歌单 id
            const match = playListUrl.match(/id=(\d+)/);
            const playlistId =match[1];
            // 生成文件路径
            const filePath = path.join(dirPath, `${playlistId}.txt`);

            // 写入 JSON
            fs.writeFileSync(filePath, JSON.stringify(musicUrls, null, 2), 'utf8');
            await sleep(3000);
        }

    } //end createPlayList();

}


module.exports = PlayList